%%
for k=1:K
   err_s(:,:,k) = abs(wh(k)-ww);
%     err_s(:,:,k) = abs(10*randn(3));
   mm(k) = min(min(err_s(:,:,k)));
%    [rr(k), cl(k)] = find(err_s(:,:,k) == mm(k) );
end

[mmv,idx] = sort(mm);

%%
for k = 1:K
    [rr(k), cl(k)] = find(err_s(:,:, idx(k)) == mmv(k) );
end

urr = unique(rr);
ucl = unique(cl);
Lurr = length(rr)-length(urr)
Lucl = length(cl)-length(ucl)


%%
if Lurr~=0 || Lucl~=0
    
%   K2 select
	err_s2 = err_s;
    err_s2(:,:, idx(1))=[];
    err_s2(rr(1), :, :)=[];
    err_s2(:, cl(1), :)=[];
    
    for k=1:K-1
       mm2(k) = min(min(err_s2(:,:,k))); 
    end
    [mmv2,idx2] = sort(mm2);

    for k = 1:K-1
        [rr(k+1), d2] = find(err_s == mmv2(k) );
        modd = mod(d2, K);
        if d2>K && modd==0
            d2 = d2/K;
        elseif d2>K && modd~=0
            d2=mod(d2,K);
        end
        cl(k+1) = d2;
    end
    
%   K3 select
    if length(unique(rr))~=K || length(unique(cl))~=K
        [rr2, cl2] = find( err_s2(:,:,idx2(1))==mmv2(1) );
        err_s3=err_s2;
        err_s3(:,:,idx2(1))=[];
        err_s3(rr2,:,:)=[];
        err_s3(:,cl2,:)=[];
        
        [rr(3), d2] = find(err_s == err_s3 );
        modd = mod(d2, K);
        if d2>K && modd==0
            d2 = d2/K;
        elseif d2>K && modd~=0
            d2=mod(d2,K);
        end
        cl(3) = d2;
    end
    
    
end
rr
cl

for k = 1:K
        pair_est_s(:, k, ith) = [phi_est_s(rr(k), ith); theta_est_s(cl(k), ith)];
end
    



%% 
% if Lurr ~= 0
%     if Lurr == 1
%         errK = min(err_s(:,:,idx(K)))
%         [errKv, errK_idx] = sort(errK)
%         [rr(K), cl(K)] = find(err_s(:,:, idx(K))==errK(errK_idx(2)))
%     elseif Lurr == 2
%         
%         errK = min(err_s(:,:,idx(K)))
%         [errKv, errK_idx] = sort(errK)
%         [rr(K), cl(K)] = find(err_s(:,:, idx(K))==errK(errK_idx(2)))
%         
%     end
%     
% elseif Lucl ~= 0
% %         find(cl==cl(idx(K)))
%         errK = min(err_s(:,:,idx(K)))
%         [err3v, err3_idx] = sort(errK)
%         [rr(3), cl(3)] = find(err_s(:,:, idx(K))==errK(err3_idx(2)))
% end
%     
% 
% for k = 1:K
%     pair_est_s(:, k, ith) = [phi_est_s(rr(k), ith); theta_est_s(cl(k), ith)];
% end
% 


%%
% clc
% aa=[1,3,3,5,5,6,2,6,9,9];
% bb=1:max(aa)
% aa(histc(aa,bb)>1)
% 
% %
% clc
% aa=[1,3,3,5,5,6,2,6,9,9];
% bb=unique(aa);
% % cc=zeros(size(bb));
% for t=1:length(bb)
%      [rrt, vvt] = find(aa==bb(t));
% end
% 
% %
% clc
% aa=[1,3,4,5,6,2,6,8,9,3,2];
% for i=1:length(aa)
%     ind(i)=length(find(aa==aa(i)));
% end
% bb=unique(aa(find(ind>=2)))
% 
% %
% aa=[1,3,3,5,5,6,2,6,9,9];
% bb=unique(aa);
% cc=histc(aa,bb)
% 


%%
AA=pair_est_s(:,:,ith);
[AA2, ppS, MSEaa] = col_permute_fit(AA, pair2)
